<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Session;
use think\Validate;

/**
 * 社区接口
 * @author wwk 2019-05-05
 */
class Community extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test', 'test1', 'ComtyHome', 'ComtyFollow', 'ComtyDetail', 'AddComment', 'FollowAdd', 'AddWorks', 'ComtyLike', 'ComtyCollection', 'Experience'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */

    /**
     * 首页社区
     *
     */
    public function ComtyHome()
    {
        header("Content-type:text/html;charset=utf-8");
        $works = Db::name('qz_works')->alias('a')
            ->join('qz_user u', 'a.uid = u.id')
            ->field('u.nickname,u.height,u.weight,u.img,a.title,a.praise_points,a.type,a.mus_or_video')
            ->where('pub_area = 1')
            ->select();
        foreach ($works as $key => $value) {
            if ($value['type'] == 1) {
                //type=1 为图片
                $works[$key]['mus_or_video'] = explode(',', $value['mus_or_video']);
            }
        }
        // echo  Db::getlastsql();
        //print_r($works);exit;
        $this->success(__('request successful'), $works);

    }

    /**
     * 首页体验
     *
     */
    public function Experience()
    {
        header("Content-type:text/html;charset=utf-8");
        //banner
        $time = time();
        $data['banner'] = Db::name('qz_app_banner')->select();
        //体验详情
        $works = Db::name('qz_works')->alias('a')
            ->join('qz_user u', 'a.uid = u.id')
            ->field('u.nickname,u.height,u.weight,u.img,a.title,a.praise_points,a.type,a.mus_or_video')
            ->where("a.end_time > $time")
            ->where('a.status = 2')
            ->where('a.pub_area = 2')
            ->select();
        foreach ($works as $key => $value) {
            if ($value['type'] == 1) {
                //type=1 为图片
                $works[$key]['mus_or_video'] = explode(',', $value['mus_or_video']);
            }
        }
        $data['works'] = $works;
        //即将揭幕  ---倒计时结束


        //锦鲤名单
        $jinli = Db::name('qz_use_activity')->alias('a')
            ->join('qz_user u', 'a.uid = u.id')
            ->join('qz_works w', 'w.id = a.wid')
            ->field('u.nickname,u.img,w.title,w.releast_time')
            ->where('a.static = 1')
            ->select();
        // echo  Db::getlastsql();
        $data['jinli'] = $jinli;
        print_r($data);
        exit;
        $this->success(__('request successful'), $works);

    }

    /**
     * 首页关注
     *
     */
    public function ComtyFollow()
    {
        header("Content-type:text/html;charset=utf-8");
        // $userid = $this->request->post('userid');
        $userid = 1;
        //我的关注  - 列表
        $Myinfo = Db::name('qz_user')->where("userid = $userid")->field('follow_id_str')->find();
        if ($Myinfo) {
            $follow_id_str = Db::name('qz_user')->field('nickname,img')->where('id', 'in', $Myinfo['follow_id_str'])->select();
        } else {
            $follow_id_str = '还没有关注任何人';
        }
        //获取关注人的发布的文章
        $works = Db::name('qz_works')->alias('a')
            ->join('qz_user u', 'a.uid = u.id')
            ->field('u.nickname,u.height,u.weight,u.img,a.title,a.praise_points,a.type,a.mus_or_video,a.collection,a.comment_num')
            ->where('u.id', 'in', $Myinfo['follow_id_str'])
            ->select();

        foreach ($works as $key => $value) {
            if ($value['type'] == 1) {
                //type=1 为图片
                $works[$key]['worlsImg'] = explode(',', $value['mus_or_video']);
            }
        }

        // echo  Db::getlastsql();
        // print_r($works);exit;
        $this->success(__('request successful'), $works);

    }

    /**
     * 喜欢
     * @w_id 文章id
     * @u_id 用户id
     * @type 类型
     */
    public function ComtyLike()
    {
        header("Content-type:text/html;charset=utf-8");
        // $u_id = $this->request->post('u_id');
        // $w_id = $this->request->post('w_id');

        $u_id = 1;
        $w_id = 1;
        //我的关注  - 列表
        $is_like = Db::name('_qz_works_like')
            ->where("u_id = $u_id")
            ->where("w_id = $w_id")
            ->where("type = 1 or type = 3")
            ->find();

        $id = $is_like['id'];
        //说明我已经关注，这个时候就取消关注
        if ($is_like) {
            if ($is_like['type'] == 1) {//如果是1 说明只是喜欢

                //为1 说明只有喜欢。那就删除数据
                $is_delete = Db::name('_qz_works_like')
                    ->where("u_id = $u_id")
                    ->where("w_id = $w_id")
                    ->delete();
                if ($is_delete) {
                    $this->success("取消喜欢");
                } else {
                    $this->error('取消喜欢失败');
                }
            } elseif ($is_like['type'] == 3) {//如果是3 说明即喜欢又收藏
                //更新type为2，即只是收藏
                $result = Db::name('_qz_works_like')->where('id', $id)->update(['type' => 2]);
                if ($result) {
                    $this->success("即喜欢又收藏，取消喜欢");
                }
            }
        } else {
            $data['u_id'] = $u_id;
            $data['w_id'] = $w_id;
            $data['type'] = 1;
            $rs = Db::name('_qz_works_like')->insert($data);
            if ($rs) {
                $pData['type'] = 2;
                $pData['wid'] = $w_id;
                $pData['content'] = '赞了你';
                $pData['form_uid'] = $u_id;//发送者
                $pData['to_uid'] = 125;//接受者
                $pData['time'] = time();
                Db::name('qz_news')->insert($pData);
                $this->error('喜欢');
            }
        }

    }

    /**
     *  收藏
     * @w_id 文章id
     * @u_id 用户id
     * @type 类型
     */
    public function ComtyCollection()
    {
        header("Content-type:text/html;charset=utf-8");
        // $u_id = $this->request->post('u_id');
        // $w_id = $this->request->post('w_id');

        $u_id = 1;
        $w_id = 1;
        //我的关注  - 列表
        $is_like = Db::name('_qz_works_like')
            ->where("u_id = $u_id")
            ->where("w_id = $w_id")
            ->where("type = 2 or type = 3")
            ->find();

        $id = $is_like['id'];

        if ($is_like) {
            if ($is_like['type'] == 2) {
                //如果是2 说明只是收藏。那就删除数据
                $is_delete = Db::name('_qz_works_like')
                    ->where("u_id = $u_id")
                    ->where("w_id = $w_id")
                    ->delete();
                if ($is_delete) {
                    $this->success("取消收藏");
                } else {
                    $this->error('取消收藏失败');
                }
            } elseif ($is_like['type'] == 3) {//如果是3 说明即喜欢又收藏
                //更新type为1，即只是喜欢
                $result = Db::name('_qz_works_like')->where('id', $id)->update(['type' => 1]);
                if ($result) {
                    $this->success("即喜欢又收藏，取消收藏");
                }
            }
        } else {
            $data['u_id'] = $u_id;
            $data['w_id'] = $w_id;
            $data['type'] = 2;
            $rs = Db::name('_qz_works_like')->insert($data);
            if ($rs) {
                $pData['type'] = 1;
                $pData['wid'] = $w_id;
                $pData['content'] = '收藏了你的作品！  ';
                $pData['form_uid'] = $u_id;//发送者
                $pData['to_uid'] = 125;//接受者
                $pData['time'] = time();
                Db::name('qz_news')->insert($pData);
                $this->error('收藏');
            }
        }

    }

    /**
     * 社区，关注 列 文章详情
     *
     */
    public function ComtyDetail()
    {
        // header("Content-type:text/html;charset=utf-8");
        // $worksid = $this->request->post('worksid');
        $worksid = 1;
        //文章详情
        $works = Db::name('qz_works')->alias('a')
            ->join('qz_user u', 'a.uid = u.id')
            ->field('u.nickname,u.height,u.weight,u.img,a.title,a.praise_points,a.type,a.mus_or_video,a.collection,a.comment_num,a.releast_time')
            ->where("a.id=$worksid")
            ->find();

        if ($works['type'] == 1) {
            //type=1 为图片
            $works['mus_or_video'] = explode(',', $works['mus_or_video']);
        }
        //评论查询
        $one_comment = Db::name('qz_works_comment')->alias('w')
            ->join('qz_user u', 'w.uid = u.id')
            ->field('u.nickname,u.img,w.time,w.comment,w.l_cid,w.level,w.id')
            ->where("w.worksid=$worksid")
            ->where("w.level=1")
            ->select();
        $tow_comment = Db::name('qz_works_comment')->alias('w')
            ->join('qz_user u', 'w.uid = u.id')
            ->field('u.nickname,u.img,w.time,w.comment,w.l_cid,w.level,w.id')
            ->where("w.worksid=$worksid")
            ->where("w.level=2")
            ->select();
        // 拼接数组
        if (is_array($one_comment)) {//如果有一级评论
            foreach ($one_comment as $key => $value) {
                if (is_array($tow_comment)) {//如果有二级评论就拼接二级
                    foreach ($tow_comment as $k => $v) {
                        if ($v['l_cid'] == $value['id']) {
                            $comment[$key]['tow_comment'][] = $v;
                        }
                    }
                } else {//如果没有二级评论就只拼接一级
                    $comment[] = $one_comment;
                }
            }
        }
        $result['works'] = $works;
        $result['comment'] = $comment;
        $this->success(__('request successful'), $result);

    }

    /**
     * 社区，关注 列 文章详情 评论接口
     * @worksid     文章id
     * @comment     评论内容
     * @l_cid   //此字段判断是否是二级评论，如果不为空说明是用户评论了 一级评论
     *
     */
    public function AddComment()
    {
        // header("Content-type:text/html;charset=utf-8");
        // $worksid = $this->request->post('worksid');
        // $comment = $this->request->post('comment');
        // $l_cid = $this->request->post('l_cid');
        $worksid = 1;
        $comment = '文章真好';
        $l_cid = '';
        $data['worksid'] = $worksid;
        $data['comment'] = $comment;
        $data['time'] = time();
        // $data['id']     =Session::get('userid');
        $data['uid'] = 121;
        //不为空说明是二级评论
        if (!empty($l_cid)) {
            $data['l_cid'] = $l_cid;
            $data['level'] = 2;
        } else {
            $data['l_cid'] = 0;
            $data['level'] = 1;
        }

        $rs = Db::name('qz_works_comment')->insert($data);
        if ($rs) {
            //评论后 给评论对象发送消息 
            //查询文章发布人
            $pData['type'] = 6;
            $pData['wid'] = $worksid;
            $pData['content'] = $comment;
            $pData['form_uid'] = 121;//发送者
            $pData['to_uid'] = 125;//接受者
            $pData['time'] = time();
            Db::name('qz_news')->insert($pData);

            $this->success(__("评论成功"));
        } else {
            $this->error('评论失败');
        }
    }

    /**
     * 关注用户接口
     * @userid        用户id
     * @follow_id     关注人id
     *
     */
    public function FollowAdd()
    {
        // header("Content-type:text/html;charset=utf-8"); 
        //$userid = $this->request->post('userid');
        $userid = 2;
        $follow_id = 4;
        if (!empty($userid)) {
            //我关注的人
            $rs = Db::name('qz_user')->field('follow_id_str')->where('userid', $userid)->find();
            //被关注用户粉丝字段
            $rs_b = Db::name('qz_user')->where('userid', $userid)->value('follow_me_id_str');
            // print_r($rs);exit;
            if (empty($rs['follow_id_str'])) {//说明之前没有关注过，这是第一个关注
                $beArr = array($follow_id);
                //数组转json
                $follow = json_encode($beArr);
                //echo($follow);die;
                //往我的信息中添加我关注的人字段值(因为是第一个关注所以直接修改)
                $up_rs = Db::name('qz_user')->where('userid', $userid)->update(['follow_id_str' => $follow]);
                $follow_num = Db::name('qz_user')->where('userid', $userid)->setInc('gz_num', 1);
                //给被关注用户加粉丝量
                //echo $rs_b;die;
                //第一个粉丝
                if ($rs_b == "") {
                    $bgArr = array($userid);
                    //数组转json
                    $follow_bg = json_encode($bgArr);
                    //往被关注人的信息中添加我的粉丝字段值(因为是第一个粉四所以直接修改)
                    $up_fs_be = Db::name('qz_user')->where('userid', $follow_id)->update(['follow_id_str' => $follow_bg]);
                    $follow_num_be = Db::name('qz_user')->where('userid', $follow_id)->setInc('fs_num', 1);
                } else {
                    //不是第一个需要追加
                    $bgArr = json_decode($rs_b);
                    $new_bgArr = array_push($bgArr, $userid);//添加元素
                    $follow_bg = json_encode($new_bgArr);
                    $up_fs_be = Db::name('qz_user')->where('userid', $follow_id)->update(['follow_id_str' => $follow_bg]);
                }
            } else {
                //我关注的人
                $arr_follow = json_decode($rs['follow_id_str'], true);
                //判断是否已经关注过,
                //关注过，取消关注
                if (in_array($follow_id, $arr_follow)) {
                    // $this->error('你已经关注过了！');
                    // 取消关注操作
                    //判断我关注的人里是否有我现在关注的人的id
                    $key = array_search($follow_id, $arr_follow);
                    if ($key !== false) {
                        //数组中移除
                        array_splice($arr_follow, $key, 1);
                    }
                    $follow = json_encode($arr_follow);
                    //获取我关注的人的粉丝字段值
                    $arr_follow_be = json_decode($rs_b, true);
                    $key = array_search($userid, $arr_follow_be);
                    if ($key !== false) {
                        //数组中移除
                        array_splice($arr_follow_be, $key, 1);
                    }
                    $follow_be = json_encode($arr_follow_be);
                    // 启动事务
                    Db::startTrans();
                    try {
                        //用户修改关注的人字段，关注的人总数-1
                        Db::name('qz_user')->where('userid', $userid)->update(['follow_id_str' => $follow]);
                        Db::name('qz_user')->where('userid', $userid)->setDec('gz_num');
                        //被用户关注的人修改粉丝量，总数-1
                        Db::name('qz_user')->where('userid', $follow_id)->update(['follow_id_str' => $follow_be]);
                        Db::name('qz_user')->where('userid', $follow_id)->setDec('fs_num');
                        // 提交事务
                        Db::commit();
                        $this->success('成功！');
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        $this->error('失败');
                    }


                }
                //用户未关注放入关注中
                array_push($arr_follow, $follow_id);
                $follow = json_encode($arr_follow);
                //被关注用户新加粉丝
                $arr_follow_be = json_decode($rs['follow_id_str'], true);
                array_push($arr_follow_be, $userid);
                $follow_be = json_encode($arr_follow);
                // 启动事务
                Db::startTrans();
                try {
                    //修改用户关注信息,总数+1
                    Db::name('qz_user')->where('userid', $userid)->update(['follow_id_str' => $follow]);
                    Db::name('qz_user')->where('userid', $userid)->setInc('gz_num', 1);
                    //修改被关注人粉丝信息,总数+1
                    Db::name('qz_user')->where('userid', $follow_id)->update(['follow_id_str' => $follow_be]);
                    Db::name('qz_user')->where('userid', $follow_id)->setInc('gz_num', 1);
                    //关注成功 往消息表发送消息
                    $pData['type'] = 3;
                    $pData['content'] = '关注了您！';
                    $pData['form_uid'] = $userid;//发送者
                    $pData['to_uid'] = $follow_id;//接受者
                    $pData['time'] = time();
                    Db::name('qz_news')->insert($pData);
                    // 提交事务
                    Db::commit();
                    $this->success('成功！');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error('失败');
                }
            }
        } else {
            $this->error('请求异常');
        }

    }

    /**
     *  发布图片文章接口
     * @uid        用户id
     * @title     标题
     * @content    内容
     * @mus_or_video     图片
     * @type     类型 图片还是视频
     *
     */
    public function AddWorks()
    {
        // header("Content-type:text/html;charset=utf-8"); 
        //$userid = $this->request->post('userid');
        $title = $this->request->post('title');
        $content = $this->request->post('content');
        // $mus_or_video = $this->request->post('mus_or_video');

        $mus_or_video = ['1.jpg', '2.jpg', '3.jpg'];
        $rule = [
            'title' => 'require|length:3,30',
            'content' => 'require|length:3,30',
            'mus_or_video' => 'require',
        ];
        $data = [
            'title' => $title,
            'content' => $content,
            'mus_or_video' => $mus_or_video,
        ];
        // $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
        // $result = $validate->check($data);
        // if (!$result) {
        //     $this->error($validate->getError());
        // }
        $jsonData = json_encode($mus_or_video);
        $insertData['title'] = $title;
        $insertData['content'] = $content;
        $insertData['mus_or_video'] = $jsonData;
        $insertData['type'] = 1;
        $insertData['releast_time'] = time();

        $rs = Db::name('qz_works')->insert($insertData);
        if ($rs) {
            $this->success(__("评论成功"));
        } else {
            $this->error('评论失败');
        }

    }

}
